<?php
declare (strict_types=1);

namespace app\index\service;


use app\index\model\AssettransferLog;
use app\index\model\AssettransferLog as admin;
use app\index\model\Configuration;
use app\index\model\User;
use app\madmin\model\IntegralRecord;
use app\madmin\model\RechargeRecord;
use app\madmin\model\UserCash;
use app\utils\TrimData;
use think\Exception;

class AssettransferService
{
    protected $user;
    protected $balance_config = [];
    protected $integral_config = [];

    public function __construct()
    {
        global $user;
        $this->user = $user;
        $configuration = Configuration::where(['type' => "Assettransfer"])->value("configuration");

        if (empty($configuration))
            throw new Exception("未完善资产转赠配置", HTTP_NOTACCEPT);
        $configuration = json_decode($configuration, true);
        $this->balance_config = $configuration['balance'];
        $this->integral_config = $configuration['integral'];
    }

    public function findAll(array $data, int $page = 1, int $size = 10)
    {

        $data = [];

        $admin = admin::field('*')->with(['user', 'gifted_user']);
        $admin = TrimData::searchDataTrim($admin, $data, ['title', 'begin_date', 'end_date']);

        $list = $admin->where('type', '=', input("type", 0))->where('user_id', '=', $this->user->id)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }


    public function sendAmount()
    {

        $money = input("amount", 0);
        $gifted_user_id = input("gifted_user_id", 0);
        $gifted_user = User::find($gifted_user_id);
        $balance_config = $this->balance_config;
        if ($balance_config['open'] != 1) {
            throw new Exception("赠送余额未开启", HTTP_NOTACCEPT);
        }
        if ($balance_config['min'] > $money) {
            throw new Exception("赠送金额不能低于{$balance_config['min']}", HTTP_NOTACCEPT);
        }
        if (empty($gifted_user)) {
            throw new Exception("赠送用户不存在", HTTP_NOTACCEPT);
        }
        $userCash = \app\index\model\UserCash::where('user_id', $this->user->id)->lock(true)->find();
        if ($userCash->total < $money) {
            throw new Exception("可赠送金额不足", HTTP_NOTACCEPT);
        }
        $this->amount($this->user, $gifted_user, $money);


        return [HTTP_SUCCESS, "赠送成功"];
    }

    public function sendIntegral()
    {
        $money = input("amount", 0);
        $gifted_user_id = input("gifted_user_id", 0);
        $integral_config = $this->integral_config;
        if ($integral_config['open'] != 1) {
            throw new Exception("赠送积分未开启", HTTP_NOTACCEPT);
        }
        if ($integral_config['min'] > $money) {
            throw new Exception("赠送金额不能低于{$integral_config['min']}", HTTP_NOTACCEPT);
        }
        $gifted_user = User::find($gifted_user_id);
        if (empty($gifted_user)) {
            throw new Exception("赠送用户不存在", HTTP_NOTACCEPT);
        }
        $userCash = \app\index\model\UserCash::where('user_id', $this->user->id)->lock(true)->find();
        if ($userCash->integral < $money) {
            throw new Exception("可赠送积分不足", HTTP_NOTACCEPT);
        }
        $this->integral($this->user, $gifted_user, $money);

        return [HTTP_SUCCESS, "赠送成功"];
    }


    public function userList(array $data, int $page = 1, int $size = 10)
    {
        $where = [];
        !empty(input('keyword')) && $where[] = ['id|mobile|nickname', 'like', '%' . input('keyword') . '%'];

        $data['status'] = 1;
        $data['mall_id'] = $this->user->mall_id;
        $admin = User::field('id,name,nickname,level,picurl,mall_id');
        $admin = TrimData::searchDataTrim($admin, $data, ['id', 'mobile', 'title', 'begin_date', 'end_date']);

        $list = $admin->where($data)->where('id', '<>', $this->user->id)->where($where)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    protected function integral($user, $gifted_user, $value): void
    {
        $value = floatval($value);
        $mid = $gifted_user->mall_id;
        $service_charge = (int)($this->getServiceCharge($this->integral_config, $value));
        $real_value = floatval($value - $service_charge);
        IntegralRecord::create([
            'mall_id' => $mid,
            'integral' => $real_value,
            'type' => 14,
            'status' => 1,
            'number' => 0,
            'commodity_id' => 0,
            'sku_id' => 0,
            'order_id' => 0,
            'user_id' => $gifted_user['id'],
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ]);
        UserCash::where('user_id', $gifted_user['id'])
            ->inc('integral', $real_value)
            ->inc('integral_total', $real_value)
            ->update(['update_time' => date('Y-m-d H:i:s')]);

        IntegralRecord::create([
            'mall_id' => $mid,
            'integral' => $value,
            'type' => 15,
            'status' => 1,
            'number' => 0,
            'commodity_id' => 0,
            'sku_id' => 0,
            'order_id' => 0,
            'user_id' => $user['id'],
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ]);
        UserCash::where('user_id', $user['id'])
            ->dec('integral', $value)
            ->dec('integral_total', $value)
            ->update(['update_time' => date('Y-m-d H:i:s')]);

        $log_data = [
            "mall_id" => $gifted_user['mall_id'],
            'type' => 1,
            'user_id' => $user['id'],
            'gifted_user_id' => $gifted_user['id'],
            'money' => $value,
            'gifted_money' => $real_value,
            'service_charge' => $service_charge,
        ];

        AssettransferLog::write($log_data);
    }

    protected function amount($user, $gifted_user, $value): void
    {

        $mid = $gifted_user->mall_id;
        $money = $value;
        #$money = floor($value / 100);
        $total = UserCash::where('user_id', $gifted_user['id'])->value('total');
        $service_charge = $this->getServiceCharge($this->balance_config, $money);

        $real_money = $money - $service_charge;
        //被赠用户记录
        $data = [
            'mall_id' => $mid,
            'user_id' => $gifted_user['id'],
            'base_in' => '',#$baseIn,
            'source_type' => 13,
            'source' => "用户{$user['nickname']}向您转赠 {$real_money}",
            'is_online' => 0,
            'type' => 0,
            'card' => '{}',
            'money' => $money,
            'service_charge' => $service_charge,
            'remark' => "用户{$user['nickname']}向您转赠 {$real_money}",
            'trade' => '',
            'pay_no' => '',
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'new_cash' => $total + $real_money,
            'old_cash' => $total
        ];
        //增加被赠用户余额
        UserCash::where('user_id', $gifted_user['id'])
            ->inc('total', $real_money)
            ->update(['update_time' => date('Y-m-d H:i:s')]);

        RechargeRecord::create($data);
        //赠送用户
        $total = UserCash::where('user_id', $user['id'])->value('total');
        $data['user_id'] = $user['id'];
        $data['source'] = "您向{$gifted_user['nickname']}转赠了{$money}";
        $data['remark'] = "您向{$gifted_user['nickname']}转赠了{$money}";
        $data['new_cash'] = $total - $money;
        $data['old_cash'] = $total;
        $data['type'] = 1;
        RechargeRecord::create($data);
        //扣除自身余额
        UserCash::where('user_id', $user['id'])
            ->dec('total', floatval($money))
            ->update(['update_time' => date('Y-m-d H:i:s')]);
        $log_data = [
            "mall_id" => $gifted_user['mall_id'],
            'type' => 0,
            'user_id' => $user['id'],
            'gifted_user_id' => $gifted_user['id'],
            'money' => $money,
            'gifted_money' => $money - $service_charge,
            'service_charge' => $service_charge,
        ];

        AssettransferLog::write($log_data);
    }

    #计算手续费
    public function getServiceCharge($config, $money)
    {
        if (empty($config['charge_status'])) {
            return 0;
        }
        $charge = $config['charge'] < 0 ? 1 : $config['charge'];
        $real_charge = $money * number_format($charge / 100, 2);
        return $real_charge;
    }
}
